package com.zhangsun.system.service.impl;

import com.zhangsun.system.service.LogoutService;
import com.zhangsun.dto.TheUser;
import com.zhangsun.service.RedisService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 登出服务
 */
@Service
public class LogoutServiceImpl implements LogoutService {

    /**
     * token参数名
     */
    @Value("${jwt.header}")
    private String header;

    /**
     * token前缀
     */
    @Value("${jwt.tokenType}")
    private String tokenType;

    @Autowired
    private RedisService redisService;

    @Override
    public void logout(HttpServletRequest request) {
        //用户退出逻辑
        Subject subject = SecurityUtils.getSubject();

        String authHeader = request.getHeader(header);
        String token = authHeader.substring(tokenType.length());
        //清空用户Token缓存
        redisService.del(token);

        //清空用户权限缓存：权限Perms和角色集合
        TheUser theUser = (TheUser) subject.getPrincipal();
        redisService.del(theUser.getUserId() + ":resource");
        redisService.del(theUser.getUserId() + ":role");
        subject.logout();
    }

}
